import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../services/notification_coordinator.dart';
import '../widgets/transgression_reporting_portal.dart';

/// 应用工具类
class AppUtils {
  /// 显示成功提示
  static void showSuccess(
    BuildContext context,
    String message, {
    String? title,
  }) {
    NotificationCoordinator.showSuccessAlert(
      context,
      message: message,
      title: title,
    );
  }

  /// 显示错误提示
  static void showError(BuildContext context, String message, {String? title}) {
    NotificationCoordinator.showErrorAlert(
      context,
      message: message,
      title: title,
    );
  }

  /// 显示警告提示
  static void showWarning(
    BuildContext context,
    String message, {
    String? title,
  }) {
    NotificationCoordinator.showWarningAlert(
      context,
      message: message,
      title: title,
    );
  }

  /// 显示信息提示
  static void showInfo(BuildContext context, String message, {String? title}) {
    NotificationCoordinator.showInfoAlert(
      context,
      message: message,
      title: title,
    );
  }

  /// 显示加载提示
  static void showLoading(
    BuildContext context, {
    String message = 'Loading...',
  }) {
    NotificationCoordinator.showLoadingAlert(context, message: message);
  }

  /// 隐藏加载提示
  static void hideLoading(BuildContext context) {
    NotificationCoordinator.hideLoadingAlert(context);
  }

  /// 显示Toast消息（保留原有方法）
  static void showToast(BuildContext context, String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        duration: const Duration(seconds: 2),
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  /// 显示确认对话框
  static void showConfirmDialog(
    BuildContext context, {
    required String message,
    String? title,
    String confirmText = 'Confirm',
    String cancelText = 'Cancel',
    required VoidCallback onConfirm,
    VoidCallback? onCancel,
  }) {
    NotificationCoordinator.showConfirmationDialog(
      context,
      message: message,
      title: title,
      confirmText: confirmText,
      cancelText: cancelText,
      onConfirm: onConfirm,
      onCancel: onCancel,
    );
  }

  /// 显示需要登录提示
  static void showLoginRequired(
    BuildContext context, {
    String? message,
    String? title,
    required VoidCallback onLogin,
    VoidCallback? onCancel,
  }) {
    NotificationCoordinator.showLoginRequiredDialog(
      context,
      message: message ?? 'This feature requires login to use',
      title: title,
      onLogin: onLogin,
      onCancel: onCancel,
    );
  }

  /// 显示编辑用户名对话框
  static void showEditUsernameDialog(
    BuildContext context, {
    required String currentUsername,
    String? title,
    String confirmText = 'Save',
    String cancelText = 'Cancel',
    required Function(String) onConfirm,
    VoidCallback? onCancel,
  }) {
    NotificationCoordinator.showEditUsernameDialog(
      context,
      currentUsername: currentUsername,
      title: title ?? 'Edit Username',
      confirmText: confirmText,
      cancelText: cancelText,
      onConfirm: onConfirm,
      onCancel: onCancel,
    );
  }

  /// 显示举报弹窗
  static void showReportDialog(
    BuildContext context, {
    String? targetId,
    String? targetType,
    Function(dynamic)? onReportSubmitted,
  }) {
    TransgressionReportingPortal.manifestReportingRealm(
      context,
      targetId: targetId,
      targetType: targetType,
      onReportSubmitted: onReportSubmitted,
    );
  }

  /// 打开网址
  static Future<void> openUrl(String url) async {
    await NotificationCoordinator.openUrl(url);
  }

  /// 显示加载对话框
  static void showLoadingDialog(BuildContext context, {String? message}) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder:
          (context) => AlertDialog(
            content: Row(
              children: [
                const CircularProgressIndicator(),
                const SizedBox(width: 16),
                Text(message ?? 'Loading...'),
              ],
            ),
          ),
    );
  }

  /// 隐藏对话框
  static void hideDialog(BuildContext context) {
    Navigator.of(context).pop();
  }

  /// 复制到剪贴板
  static Future<void> copyToClipboard(String text) async {
    await Clipboard.setData(ClipboardData(text: text));
  }

  /// 震动反馈
  static void vibrate() {
    HapticFeedback.lightImpact();
  }

  /// 格式化文件大小
  static String formatFileSize(int bytes) {
    if (bytes < 1024) {
      return '$bytes B';
    } else if (bytes < 1024 * 1024) {
      return '${(bytes / 1024).toStringAsFixed(1)} KB';
    } else if (bytes < 1024 * 1024 * 1024) {
      return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
    } else {
      return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB';
    }
  }

  /// 格式化时间
  static String formatTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }

  /// 验证邮箱格式
  static bool isValidEmail(String email) {
    return RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(email);
  }

  /// 验证手机号格式
  static bool isValidPhone(String phone) {
    return RegExp(r'^1[3-9]\d{9}$').hasMatch(phone);
  }

  /// 生成随机字符串
  static String generateRandomString(int length) {
    const chars =
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    final random = DateTime.now().millisecondsSinceEpoch;
    String result = '';

    for (int i = 0; i < length; i++) {
      result += chars[(random + i) % chars.length];
    }

    return result;
  }

  /// 获取屏幕尺寸
  static Size getScreenSize(BuildContext context) {
    return MediaQuery.of(context).size;
  }

  /// 获取状态栏高度
  static double getStatusBarHeight(BuildContext context) {
    return MediaQuery.of(context).padding.top;
  }

  /// 获取底部安全区域高度
  static double getBottomSafeAreaHeight(BuildContext context) {
    return MediaQuery.of(context).padding.bottom;
  }

  /// 判断是否为深色主题
  static bool isDarkTheme(BuildContext context) {
    return Theme.of(context).brightness == Brightness.dark;
  }
}
